package edu.pku.sei.mte.modification;

import java.util.LinkedList;

import edu.pku.sei.mte.modification.command.ModelModificationCommand;

public class ModelModificationManager {
	
	private LinkedList<ModelModificationCommand> completedCommands = new LinkedList<ModelModificationCommand>();
	
	private LinkedList<ModelModificationCommand> undoCommands = new LinkedList<ModelModificationCommand>();
	
	public ModelModificationCommand getCurrentCommand(){
		if(! completedCommands.isEmpty())
			return completedCommands.peek();
		return null;
	}
	public void rollBackTo(ModelModificationCommand command){
		while(!completedCommands.peek().equals(command) && !completedCommands.isEmpty()){
			ModelModificationCommand c = completedCommands.pop();
			c.undo();
			undoCommands.add(c);
		}
	}
	
	public void addNewCommand(ModelModificationCommand command){
		if(command != null){
			completedCommands.push(command);
			if(!undoCommands.isEmpty())
				undoCommands.clear();
		}
	}
	
	public void redo(ModelModificationCommand command) throws Exception{
		while(!undoCommands.isEmpty()){
			ModelModificationCommand c = undoCommands.pop();
			c.execute();
			if(c.equals(command))
				break;
		}
	}
	
	public void clear(){
		completedCommands.clear();
		undoCommands.clear();
	}
}
